package com.df.barcodescaning.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

import com.df.barcodescaning.MyApplication;
import com.df.barcodescaning.R;
import com.df.barcodescaning.bean.UserData;
import com.df.barcodescaning.bean.UserGroup;
import com.df.barcodescaning.widget.ClearEditText;

import java.util.Map;

import static com.df.barcodescaning.R.id.username;
import static com.df.barcodescaning.ui.UserManageActivity.KEY_SERIAL_USER_GROUP;

/**
 * Created by G on 2018/5/31.
 * 登录页面
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

    private ClearEditText userNameView;
    private ClearEditText passwordView;
    private CheckBox checkPwd;
    private Button loginButton;
    private TextInputLayout userNameTextInputLayout;
    private TextInputLayout passwordTextInputLayout;

    private UserGroup userGroup;
    private UserData userData;

    private Map<String, UserData> userMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setTitle(R.string.app_name);
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        userGroup = MyApplication.getInstance().getRegistedUser();
        userMap = userGroup.getValues();
        if (userData != null && userData.isManager()) { //管理员账户时,不可保存密码
            passwordView.setText("");
        }
    }

    protected void init() {
        userNameTextInputLayout= (TextInputLayout) findViewById(username);
        userNameView = (ClearEditText)userNameTextInputLayout.getEditText();
        passwordTextInputLayout = (TextInputLayout) findViewById(R.id.password);
        passwordView = (ClearEditText) passwordTextInputLayout.getEditText();
        checkPwd = (CheckBox) findViewById(R.id.checkbox_id);
        loginButton= (Button) findViewById(R.id.bt_login);
        loginButton.setOnClickListener(this);
    }

    /**
     * 登录
     */
    private void login(){
        userNameTextInputLayout.setError(" ");
        passwordTextInputLayout.setError(" ");
        final String username = userNameView.getText().toString().trim();
        if(TextUtils.isEmpty(username)){
            userNameTextInputLayout.setError(getString(R.string.msg_login_username_null));
            return;
        }
        final String pwd= passwordView.getText().toString().trim();
        if(TextUtils.isEmpty(pwd)){
            passwordTextInputLayout.setError(getString(R.string.msg_login_passwork_null));
            return;
        }
        if (userMap != null && userMap.size() > 0) {
            userData = userMap.get(username);
        }
        if (userData == null) {
            userNameTextInputLayout.setError(getString(R.string.msg_login_username_inexist));
            return;
        }
        if (!userData.getUserPsw().equals(pwd)) {
            passwordTextInputLayout.setError(getString(R.string.msg_login_username_err));
            return;
        }
        if (userData.isManager()) { //管理员
            Intent intent = new Intent(this, UserManageActivity.class);
            intent.putExtra(KEY_SERIAL_USER_GROUP, userGroup);
            startActivity(intent);
        } else {    //普通注册用户登录
//            if (checkPwd.isChecked())
                MyApplication.getInstance().saveLoggedUser(userData);
            startActivity(new Intent(this, ItemSelectActivity.class));
            finish();
        }




//        RequestConfig config = new RequestConfig();
//        config.setTipInfoLayout(getTipInfoLayout())
//                .setMainBody(getMainBody())
//                .setIsCover(false)
//                .setShowProgressDialog(true);
//
//        Map<String,String> requestParams = new HashMap<String,String>();
//        requestParams.put("email",username);
//        requestParams.put("password",pwd);
//        new RequestClient(LoginActivity.this, config){
//            @Override
//            public void loadSuccess(String result) {
//                Member member = JSONParseUtils.parseObject(result, Member.class);
//                OsApplication.member = member;
//                if(checkPwd.isChecked()){
//                    OsApplication.instance.saveMember(member);
//                }
//
//                //发送广播，更新主视图
//                Intent loginIntent = new Intent();
//                Bundle loginBundle = new Bundle();
//                loginBundle.putInt(IntentConstants.TYPE, Constants.TYPE_LOGIN);
//                loginIntent.putExtras(loginBundle);
//                loginIntent.setAction(IntentConstants.LOGIN_BROADCAST_ACTION);
//                LocalBroadcastManager.getInstance(LoginActivity.this).sendBroadcast(loginIntent);
//
//                //页面跳转处理
//                Bundle bundle=getIntent().getExtras();
//                if(bundle!=null){
//                    boolean isReturn=bundle.getBoolean(IntentConstants.LOGIN_RETURN, false);
//                    boolean isValidateLogin=bundle.getBoolean(IntentConstants.LOGIN_VALIDATE, false);
//                    if(isReturn){  //登录成功，返回resultCode
//                        int resultCode=bundle.getInt(IntentConstants.LOGIN_RESULT_CODE, 0);
//                        setResult(resultCode);
//                    }else if(isValidateLogin){   //判断用户是否从其它页面需要用户登录才能打开的页面
//                        //登录成功去往真实目标页面
//                        Class<?> targetClazz=(Class<?>) bundle.getSerializable(IntentConstants.LOGIN_TARGET_CLASS);
//                        Intent intent = getIntent();   //保留Intent不变，因此Intent有上一个页面有值需要传给最终页面，
//                        intent.setClass(LoginActivity.this, targetClazz);
//                        IntentUtils.startActivity(LoginActivity.this, intent);
//                    }else{   //从用户登录页而来，应进入个人中心页
//                        IntentUtils.startActivity(LoginActivity.this, MemberActivity.class);
//                    }
//                }else{  //从用户登录页而来，应进入个人中心页
//                    IntentUtils.startActivity(LoginActivity.this, MemberActivity.class);
//                }
//
//                finish();
//            }
//
//            @Override
//            public void loadFail() {}
//        }.post(RequestAPI.LOGIN, requestParams);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_login:
                login();
//                startActivity(new Intent(this, UserManageActivity.class));
                break;
        }
    }

}
